import { getDictDataByType } from "@/api/admin/system/dict";

export function getLocalStorage(key: string) {
  return localStorage.getItem(key);
}

export function removeLocalStorage(key: string) {
  localStorage.removeItem(key);
}

export function setLoclastorage(key: string, val: string) {
  localStorage.setItem(key, val);
}

/**
 *
 * @param data 数据源
 * @param id字段 默认 'id'
 * @param parent_id 父节点字段 默认 'parent_id'
 * @param children 孩子节点字段 默认 'children'
 * @param rootId 根Id 默认 0
 * @returns {{obj, list: Array}}
 */
export function handleTree(
  data: any[],
  id = "id",
  parent_id = "parent_id",
  children = "children",
  rootId = 0
) {
  const obj: any = {};
  data.forEach((item: any) => {
    item[children] = [];
    obj[item[id]] = item;
  });
  const tree: any[] = [];
  data.forEach((list) => {
    if (list[parent_id] !== rootId) {
      if (obj[list[parent_id]]) {
        obj[list[parent_id]][children].push(list);
      }
    } else {
      tree.push(list);
    }
  });
  Object.keys(obj).forEach((key) => {
    if (!obj[key].children.length) {
      delete obj[key].children;
    }
  });
  return {
    tree,
    obj,
  };
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params: any) {
  let result = "";
  Object.keys(params).forEach((key) => {
    if (
      !Object.is(params[key], undefined) &&
      !Object.is(params[key], null) &&
      !Object.is(JSON.stringify(params[key]), "{}")
    ) {
      result +=
        encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
    }
  });
  return result;
}

// 递归拷贝 (类型判断)
export function deepClone(value: any, hash = new WeakMap()) {
  // 弱引用，不要用map
  // null 和 undefiend 是不需要拷贝的
  if (value == null) {
    return value;
  }
  if (value instanceof RegExp) {
    return new RegExp(value);
  }
  if (value instanceof Date) {
    return new Date(value);
  }
  // 函数是不需要拷贝
  if (typeof value != "object") return value;
  const obj = new value.constructor(); // [] {}
  // 说明是一个对象类型
  if (hash.get(value)) {
    return hash.get(value);
  }
  hash.set(value, obj);
  for (const key in value) {
    // in 会遍历当前对象上的属性 和 __proto__指代的属性
    // 补考呗 对象的__proto__上的属性
    if (value.hasOwnProperty(key)) {
      // 如果值还有可能是对象 就继续拷贝
      obj[key] = deepClone(value[key], hash);
    }
  }
  return obj;
}

function curring(fn: Function) {
  // 存储每次调用的时候传入的变量
  const inner = (args: any[] = []) => {
    // 存储每次调用时传入的参数
    return args.length >= fn.length
      ? fn(...args)
      : (...userArgs: any[]) => inner([...args, ...userArgs]); // 递归返回函数
  };
  return inner();
}
// 我们的柯里化登场： 让函数变得更具体一些，反柯里化： 让函数范围变的更大一些
function isType(typing: string, val: any) {
  return Object.prototype.toString.call(val) == `[object ${typing}]`;
}

interface IType {
  isString?: any;
  isNumber?: any;
  isBoolean?: any;
  isNull?: any;
  isUndefined?: any;
  isArray?: any;
  isObject?: any;
  [key: string]: any;
}

export const checkType: IType = {};
["String", "Number", "Boolean", "Null", "Undefined", "Array", "Object"].forEach(
  (type) => {
    checkType["is" + type] = curring(isType)(type);
  }
);

// 获取字典数据
export const handleDictDataByType = async (type: string) => {
  const { data } = await getDictDataByType(type);
  return data.lists.map((item) => ({
    value: item.dict_value,
    label: item.dict_label,
  }));
};

// 获取数据
export const getDictDataByVal = (list: any[], val: string) => {
  return list?.find((item) => item.value === val)?.label;
};
